package cn.lutu.adapter.controller;

import cn.lutu.alipay.pojo.dto.AlipayOrderDTO;
import cn.lutu.alipay.service.AlipayOrderService;
import cn.lutu.alipay.service.AlipayService;
import cn.lutu.alipay.pojo.entity.AlipayOrder;
import cn.lutu.util.BaseResult;
import cn.lutu.util.SysConstant;
import cn.lutu.util.response.ResultVO;
import cn.lutu.util.response.StatusCode;
import com.alipay.api.AlipayApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Api(tags = "支付宝支付")
@Slf4j
public class AliPayController {

    @Autowired
    private AlipayService service;

    @Autowired
    AlipayOrderService orderService;
    /**
     * 支付方法
     */
    @ApiOperation("订单创建")
    @PostMapping("/trade")
    public void alipay(@RequestBody AlipayOrderDTO alipayOrderDTO, HttpServletResponse response) throws IOException {
      String trade=service.createTrade(alipayOrderDTO);
      response.setContentType("text/html;charset=utf-8");
      response.getWriter().println(trade);
    }

    /**
     * 异步通知
     */
    @ApiOperation("处理订单")
    @RequestMapping("/trade/notify")
    public void tradeNotify(@RequestParam Map<String,String> params,@ApiIgnore HttpServletResponse response) throws AlipayApiException, IOException {
        log.info("开始处理异步通知请求");
        //1.验证证书上的公钥是否一直
        boolean signVerified=service.aliSignature(params);
         if(!signVerified){
             log.info("验证失败");

         }
        System.out.println(1);
         //2.商户发送的订单号是否一致
        String out_trade_no=params.get("out_trade_no");
        AlipayOrder order= orderService.getByTradeNo(out_trade_no);
        System.out.println(order);
         if(order==null){
             log.info("订单不存在");

         }
        System.out.println(2);
         //3.验证金额是否一致
         String total_amount=params.get("total_amount");
         System.out.println("支付宝返回的金额为："+total_amount);
         Double parseDouble=Double.parseDouble(total_amount);
         System.out.println(parseDouble);
         Double totalAmount=order.getTotalAmount();
        System.out.println("数据库订单金额："+totalAmount);
         if(!parseDouble.equals(totalAmount)){
             log.info("验证失败，金额不一致");

         }
        System.out.println(3);
         //4.验证状态是否一致
        String trade_status=params.get("trade_status");
         if(!SysConstant.TRADE_SUCCESS.equals(trade_status)){
             log.info("验证失败，交易状态不一致");
         }
        System.out.println(4);
         //5.修改订单状态
        orderService.updateOrderStatus(order,SysConstant.TRADE_SUCCESS);
        System.out.println("修改订单状态成功");

        response.sendRedirect("http://localhost:9090/success?id="+order.getOrderNo());
    }

    @GetMapping("selectById")
    @ApiOperation("根据订单号查询订单")
    public ResultVO selectById(String orderNo){
        log.debug("开始根据订单号查询订单");
        AlipayOrder order = orderService.getByTradeNo(orderNo);
        return ResultVO.ok(order);
    }

    @PostMapping("{orderNo}/status")
    @ApiOperation("根据订单号查询订单状态")
    public ResultVO orderStatus(@PathVariable String orderNo){
        log.debug("开始根据订单号查询订单状态,参数为{}",orderNo);
        AlipayOrder order = orderService.getByTradeNo(orderNo);
        if(SysConstant.TRADE_SUCCESS.equals(order.getStatus())){
            return ResultVO.ok();
        }else {
            return ResultVO.fail(StatusCode.OPERATION_FAILED,"未检测到付款，请重试");
        }

    }


}
